package com.example.helloworldtext2.utils;

import static android.content.ContentValues.TAG;

import android.content.Context;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.example.helloworldtext2.model.Article;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.MediaItem;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.ProgressiveMediaSource;
import com.google.android.exoplayer2.source.hls.HlsMediaSource;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DefaultDataSource;
import com.google.android.exoplayer2.ui.StyledPlayerView;


public class VideoPlayManager {
    private volatile static VideoPlayManager mInstance = null;
    private Context mContext;
    private ExoPlayer player;
//视频数据
    private Article article;
//    播放显示器
    private StyledPlayerView playerView;
    private SeekBar videoProgress;
    private ImageView playButton;
    private ImageView coverImage;

    // 添加定时器计算视频进度
    private Handler handler = new Handler(Looper.getMainLooper());
    private Runnable updateProgressRunnable = new Runnable() {
        @Override
        public void run() {
            if (player != null && player.getPlaybackState() == Player.STATE_READY) {
                long currentPosition = player.getCurrentPosition();
                long duration = player.getDuration();

                // 更新UI进度条等
                updateProgressUI(currentPosition, duration);

                // 每秒更新一次
                handler.postDelayed(this, 1000);
            }
        }
    };


    /**
     * 双重检测
     * @return
     */
    public static VideoPlayManager getInstance(Context context) {
        if (mInstance == null) {
            synchronized (VideoPlayManager.class) {
                if(mInstance == null) {
                    mInstance = new VideoPlayManager(context);
                }
            }
        }
        return mInstance;
    }

    public VideoPlayManager(Context context) {
        this.mContext = context;
    }

    /**
     * 开始播放
     */
    public void startPlay() {
//        stopPlay();
//        if(mCurVideoPlayTask == null) {
//            Log.e("Video_Play_TAG", "start play task is null");
//            return;
//        }
//
//        mSimpleExoPlayer = new ExoPlayer.Builder(mContext).build();
//        // 准备要播放的媒体资源
//        MediaItem mediaItem = MediaItem.fromUri(mCurVideoPlayTask.getVideoUrl());
//        mSimpleExoPlayer.setMediaItem(mediaItem);
//
//        //隐藏播放工具
//        mCurVideoPlayTask.getSimpleExoPlayerView().setUseController(false);
//        //设置播放视频的宽高为Fit模式
//        mCurVideoPlayTask.getSimpleExoPlayerView().setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_FIT);
//        //绑定player和playerView
//        mCurVideoPlayTask.getSimpleExoPlayerView().setPlayer(mSimpleExoPlayer);
//        mSimpleExoPlayer.setPlayWhenReady(true);
//
//        // 准备播放器
//        mSimpleExoPlayer.prepare();
//        mSimpleExoPlayer.play();
        stopPlay();
        Log.d("start","开始播放");
        // 初始化ExoPlayer
        initPlayer(mContext);
        // 设置视频URI
        String videoUrl = article.getVideoUrl();
        Log.d(TAG, "Video URL: " + videoUrl);

        // 检查URL是否为空
        if (videoUrl == null || videoUrl.isEmpty()) {
            Log.e(TAG, "Video URL is null or empty");
            Toast.makeText(mContext, "视频URL无效", Toast.LENGTH_SHORT).show();
            return;
        }

        Uri videoUri = Uri.parse(videoUrl);

        // 创建带缓存的数据源工厂，使用同步块保护缓存访问
        DataSource.Factory dataSourceFactory = new DefaultDataSource.Factory(mContext);
        // 根据URL扩展名选择合适的媒体源
        MediaSource mediaSource;
        if (videoUrl.toLowerCase().endsWith(".m3u8")) {
            // 使用HLS媒体源处理M3U8流媒体
            mediaSource = new HlsMediaSource.Factory(dataSourceFactory)
                    .createMediaSource(MediaItem.fromUri(videoUri));
        } else {
            // 使用渐进式媒体源处理普通视频文件
            mediaSource = new ProgressiveMediaSource.Factory(dataSourceFactory)
                    .createMediaSource(MediaItem.fromUri(videoUri));
        }

        // 准备播放器
        player.setMediaSource(mediaSource);
        player.prepare();
        // 视频准备好的监听器
        player.addListener(new Player.Listener() {
            @Override
            public void onPlaybackStateChanged(int playbackState) {
                if (playbackState == Player.STATE_READY) {
                    coverImage.setVisibility(View.GONE);
                    player.play();

                    // 开始更新进度
                    startProgressUpdate();
                } else if (playbackState == Player.STATE_ENDED) {
                    // 播放完成后重新开始播放
                    player.seekTo(0);
                    player.play();
                }
            }

            @Override
            public void onPlayerError(@NonNull com.google.android.exoplayer2.PlaybackException error) {
                Log.e(TAG, "Player error: " + error.getMessage(), error);
                Toast.makeText(mContext, "播放视频时出错: " + error.getMessage(), Toast.LENGTH_LONG).show();
                // 停止进度更新
                stopProgressUpdate();
                coverImage.setVisibility(View.VISIBLE);
            }
        });
    }
    private void initPlayer(Context context) {
        if (player == null) {
            player = new ExoPlayer.Builder(context).build();
            playerView.setPlayer(player);
            player.setRepeatMode(com.google.android.exoplayer2.Player.REPEAT_MODE_ONE);
        }
    }
    public VideoPlayManager setCurVideoPlayTask(Article article, StyledPlayerView playerView, SeekBar videoProgress, ImageView playButton, ImageView coverImage){
        this.article = article;
        this.playerView = playerView;
        this.videoProgress = videoProgress;
        this.playButton = playButton;
        this.coverImage = coverImage;
        return mInstance;
    }

    /**
     * 停止播放
     */
    /**
     * 开始更新进度
     */
    private void startProgressUpdate() {
        // 移除之前的消息，防止重复
        handler.removeCallbacks(updateProgressRunnable);
        // 开始更新进度
        handler.post(updateProgressRunnable);
    }
    
    /**
     * 停止更新进度
     */
    private void stopProgressUpdate() {
        handler.removeCallbacks(updateProgressRunnable);
    }
    
    /**
     * 更新进度UI（需要子类实现具体逻辑）
     * @param currentPosition 当前位置
     * @param duration 总时长
     */
    private void updateProgressUI(long currentPosition, long duration) {
        // 具体的UI更新逻辑应该在这里实现
         // 具体的UI更新逻辑
        if (videoProgress != null) {
            if (duration > 0) {
                int progress = (int) ((currentPosition * 100) / duration);
                videoProgress.setProgress(progress);
            }
        }
        // 这个方法需要在子类中重写或者通过回调实现
    }
    /**
     * 切换播放状态（播放/暂停）
     */
    public void togglePlayback() {
        if (player != null) {
            if (player.isPlaying()) {
                pausePlay();
            } else {
                resumePlay();
            }
        } else {
            playButton.setVisibility(View.GONE);
            startPlay();
        }
    }

    public void stopPlay() {
//        coverImage.setVisibility(View.VISIBLE);
        // 停止进度更新
        stopProgressUpdate();
        if(player != null) {
            player.release();
            player = null;

        }
    }

    public void resumePlay() {
        if(player != null) {
            player.setPlayWhenReady(true);
            // 恢复进度更新
            startProgressUpdate();
            playButton.setVisibility(View.GONE);
        } else {
            startPlay();
        }
    }

    public void pausePlay() {
        if(player != null) {
            playButton.setVisibility(View.VISIBLE);
            player.setPlayWhenReady(false);
            // 暂停进度更新
            stopProgressUpdate();
        }
    }
}
